#!/usr/bin/env python
# -*- coding: utf-8 -*-
# datetime: 15/11/2023 下午10:54
# Author: name
# File: chart_gpt.py
# ide: PyCharm
# description:
import time

from pywebio.output import *
from pywebio.pin import *

from frontend.menus import show_menus
import requests
import base64

with open("frontend/imgs/chatgpt.jpg", "rb") as img_file:
    img_data = base64.b64encode(img_file.read()).decode('utf-8')


def send_request(question):
    headers = {
        'authority': 'api.binjie.fun',
        'accept': 'application/json, text/plain, */*',
        'accept-language': 'zh-CN,zh;q=0.9',
        'cache-control': 'no-cache',
        'content-type': 'application/json',
        'origin': 'https://chat.jinshutuan.com',
        'pragma': 'no-cache',
        'referer': 'https://chat.jinshutuan.com/',
        'sec-ch-ua': '"Google Chrome";v="119", "Chromium";v="119", "Not?A_Brand";v="24"',
        'sec-ch-ua-mobile': '?0',
        'sec-ch-ua-platform': '"Windows"',
        'sec-fetch-dest': 'empty',
        'sec-fetch-mode': 'cors',
        'sec-fetch-site': 'cross-site',
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/119.0.0.0 Safari/537.36',
    }

    json_data = {
        'prompt': f'{question}',
        'userId': '#/chat/1700144017463',
        'network': True,
        'system': '',
        'withoutContext': False,
        'stream': False,
    }

    response = requests.post('https://api.binjie.fun/api/generateStream',headers=headers,
                             json=json_data)
    print(response.encoding)
    print(response.text.encode('latin-1').decode('utf-8'))
    return response.text.encode("latin-1").decode("utf-8")


def get_result():
    kw = pin.kw
    if kw:
        pin_update("kw", value="")
        put_markdown(f'我：{time.strftime("%Y-%m-%d %H:%M:%S")}\n<div style="background-color: #CBFDFB;">{kw}？</div>',
                     scope="scrollable")
        result = send_request(kw)
        html_code = f'<img src="data:image/jpeg;base64,{img_data}" width="30" height="30">：{time.strftime("%Y-%m-%d %H:%M:%S")}'
        put_html(html_code, scope="scrollable")
        if result:
            markdown_text = f'<div style="background-color: #E5E5F5;">{result}</div>'
        else:
            markdown_text = f'<div style="background-color: #E5E5F5;">出错了请重试</div>'
        put_markdown(markdown_text, scope="scrollable")
    # pin_update("show_data",value=put_markdown(markdown_text))


def reset():
    clear("scrollable")
    pin_update("kw", value="")


def html_chart_gpt():
    """
    ChatGPT

    :return:
    """
    show_menus()
    put_tabs([
        {'title': 'ChartGPT', 'content': [
            put_scrollable(put_scope('scrollable'), height=700, keep_bottom=True),
            put_row([
                put_input("kw"),
                None,
                put_button('发送', onclick=lambda: get_result()),
                None,
                put_button("重置", onclick=lambda: reset())
            ], size="85% 2%")
        ]},

    ], scope="data_list")
